//
//  SendWeiboViewController.m
//  微blog
//
//  Created by Jorn.Wu on 15/9/1.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "SendWeiboViewController.h"
#import "ThemeButton.h"
#import "MMDrawerController.h"
#import "ThemeImageView.h"
#import "ThemeManager.h"
#import "DataService.h"
#import "AFNetworking.h"
#import <CoreLocation/CoreLocation.h>
#import "DataService.h"
#import "FaceScrollView.h"
#import "ZoomImageView.h"

@interface SendWeiboViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,CLLocationManagerDelegate,FaceViewDelegate,ZoomImageViewDelegate>

/**
 * 输入框
 */
@property (nonatomic, strong) UITextView *inputView;

/**
 * 工具条
 */
@property (nonatomic, strong) ThemeImageView *toolBar;

/**
 * 缩略图（用来放大缩小预览图）
 */
@property (nonatomic, strong) ZoomImageView *zoomImageView;

/**
 * 定位manager
 */
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UILabel *locationLabel;//显示当前位置

/**
 * 表情面板
 */
@property (nonatomic, strong) FaceScrollView *faceViewPanel;
@property (nonatomic, assign) BOOL isShowFacePanel;//表情符号是否是显示的

@end

@implementation SendWeiboViewController{
    UIImage *_sendImage;
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        /**
         * 注册通知接收
         */
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
        
        self.navigationController.navigationBar.translucent = NO;
        
        [self changedInputViewBgColor];
        
        
    }
    return  self;
    
}


/**
 * 更改toolBar的位置
 */
- (void)keyBoardWillShow:(NSNotification *)noti{
    
    //1 取出键盘frame
    NSValue *bounsValue = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect frame = [bounsValue CGRectValue];
    //2 键盘y坐标
    CGFloat y = frame.origin.y;
    
    if (_isShowFacePanel) {//是显示的，则先隐藏
        [self hideFaceView];
        _isShowFacePanel = !_isShowFacePanel;
    }
    //3 调整视图的高度
    _toolBar.bottom = y - 64;
    
    
}

/**
 * 更改输入框的背景
 */
- (void)changedInputViewBgColor{
    self.inputView.backgroundColor = [UIColor colorWithPatternImage:[[ThemeManager defualtManager] getThemeImage:@"bg_compose.ipg"]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addNavBarItems];
    [self addInputView];
    [self addToolBar];
    
    [self.inputView becomeFirstResponder];
}

/**
 * 添加导航按钮
 */
- (void)addNavBarItems{
    
    /**
     * 封装的方法
     */
    [self addNavigationThemeItemWithOrientation:@"left" title:nil image:@"button_icon_close.png" action:@selector(closeAction)];
    [self addNavigationThemeItemWithOrientation:@"right" title:nil image:@"button_icon_ok.png" action:@selector(sendAction)];
    
}

/**
 * 取消
 */
- (void)closeAction{
    
//    [self.inputView resignFirstResponder];
//    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
    //通过UIWindow找到  MMDRawer(这种方法更安全)
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    if ([window.rootViewController isKindOfClass:[MMDrawerController class]]) {
        MMDrawerController *mmDrawer = (MMDrawerController *)window.rootViewController;
        
        [mmDrawer closeDrawerAnimated:YES completion:NULL];
    }
    [_inputView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:NULL];
    
}

/**
 * 发送
 */
- (void)sendAction{
    
    NSString *text = _inputView.text;
    NSString *error = nil;
    if (text.length == 0) {
        error = @"微博内容为空";
    }
    else if(text.length > 140) {
        error = @"微博内容大于140字符";
    }
    if (error != nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:error delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    
    //发送（添加状态栏显示状态）
    AFHTTPRequestOperation *operation =  [DataService sendWeibo:text image:_sendImage block:^(id result) {
        NSLog(@"发送成功");
        //状态栏显示
        [self showStatusTip:@"发送成功" show:NO operation:nil];
        
    }];
    
    [self showStatusTip:@"正在发送..." show:YES operation:operation];
    [self closeAction];
    
    
  
    
}

#pragma mark UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"])  //按回车发送
    {
        [self sendAction];
        return YES;
    }
    return NO;
}

- (void)textViewDidChange:(UITextView *)textView{

    
    if ([textView.text length] > 140) { //如果输入框内容大于140则弹出警告
        textView.text = [textView.text substringToIndex:140];//只取前140个字符
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"不能超过140个字符！"
                                                       delegate:nil
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil];//警告框
        [alert show];
        
    }

}


/**
 * 添加输入文本框22
 */
- (void)addInputView{
    
    // 文本输入视图
    _inputView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 120)];
    _inputView.font = [UIFont systemFontOfSize:16.0f];
    _inputView.editable = YES;
    
    
    _inputView.layer.cornerRadius = 10;
    _inputView.layer.borderWidth = 2;
    _inputView.layer.borderColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_inputView];
    

}

/**
 * 添加工具条
 */
- (void)addToolBar{
    //2 编辑工具栏
    _toolBar = [[ThemeImageView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 60, kScreenWidth, 60)];
    _toolBar.imageName = @"compose_option_bg_9";
    _toolBar.userInteractionEnabled = YES;
    [self.view addSubview:_toolBar];
    //3.创建多个编辑按钮
    NSArray *imgs = @[
                      @"compose_toolbar_1.png",
                      @"compose_toolbar_4.png",
                      @"compose_toolbar_3.png",
                      @"compose_toolbar_5.png",
                      @"compose_toolbar_6.png"
                      ];
    
    CGFloat s = 10; //间距
    CGFloat w = (kScreenWidth - s * (imgs.count + 1)) * 1.0/ imgs.count;
    CGFloat h = 40;
    
    for (int i=0; i<imgs.count; i++) {
        NSString *imgName = imgs[i];
        ThemeButton *button = [[ThemeButton alloc] initWithFrame:CGRectMake(s + (w + s) * i, 20, w, h)];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 100 + i;
        button.normalImageName = imgName;
        [_toolBar addSubview:button];
    }
    
    //显示位置信息
    _locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 20)];
    _locationLabel.backgroundColor = [UIColor lightGrayColor];
    _locationLabel.textColor = [UIColor blackColor];
    _locationLabel.font = [UIFont systemFontOfSize:15];
    _locationLabel.hidden = YES;    //先隐藏
    [_toolBar addSubview:_locationLabel];
}

- (void)buttonAction:(ThemeButton *)btn{
    
    if (btn.tag == 100) {
        [_inputView resignFirstResponder];
        //选择照片
        [self selectPhoto];
        
    }else if(btn.tag == 103){
        //定位
        [self location];
    }else if(btn.tag == 104) {  //显示、隐藏表情
        
        BOOL isFirstResponder = _inputView.isFirstResponder;
        
        if (!_isShowFacePanel) {//开始时隐藏的
            
            //输入框是否是第一响应者，如果是，说明键盘已经显示
            if (isFirstResponder) {
                //先隐藏键盘
                [_inputView resignFirstResponder];
            }
            
            [self showFaceView];
            
            _isShowFacePanel = !_isShowFacePanel;
            
        }else {//开始时显示的
            
            [self hideFaceView];
            
            _isShowFacePanel = !_isShowFacePanel;
            
        }
        
    }
    
    
}


/**
 * 表情视图的显示和隐藏
 */
- (void)showFaceView{

    //创建表情面板
    if (_faceViewPanel == nil) {
        
        
        _faceViewPanel = [[FaceScrollView alloc] init];
        [_faceViewPanel setFaceViewDelegate:self];
        //放到底部
        _faceViewPanel.top  = kScreenHeight;
        [self.view addSubview:_faceViewPanel];
    }
    
    //显示表情
    [UIView animateWithDuration:0.3 animations:^{
        
        _faceViewPanel.bottom = kScreenHeight;
        //重新布局工具栏、输入框
        _toolBar.bottom = _faceViewPanel.top;
        
    }];
    
}

- (void)hideFaceView{
    //隐藏表情
    [UIView animateWithDuration:0.3 animations:^{
        _faceViewPanel.top = kScreenHeight - 64;
        _toolBar.bottom = kScreenHeight - 64;
        
    }];
}


#warning ---------未添加到文本中，只打印名称
#pragma mark FaceViewDelegate
- (void)faceDidSelect:(NSString *)text{
    NSLog(@"选中了%@",text);
    
}



/**
 * 定位的方法
 */
- (void)location{
    
    /*
        修改 info.plist 增加以下两项
        NSLocationWhenInUseUsageDescription  BOOL YES
        NSLocationAlwaysUsageDescription         string “提示描述”
     */
    
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        if (kVersion > 8.0) {
            //获取授权使用地理位置服务
            [_locationManager requestWhenInUseAuthorization];
        }
    }
    
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
   
}

#pragma mark CLLocationManagerDelegate
/**
 * 定位完成时调用
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

    //停止定位
    [_locationManager stopUpdatingLocation];
    //取得位置信息
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;//结构体
    
//    //测试:
//    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(30.320278, 120.338889);
    
    NSLog(@"经度%lf,纬度%lf",coordinate.longitude,coordinate.latitude);
    
    //地理位置反编码，通过坐标信息获取 位置详情
    
    //一 新浪位置反编码 接口说明  http://open.weibo.com/wiki/2/location/geo/geo_to_address
    
    NSString *coordinateStr = [NSString stringWithFormat:@"%f,%f",coordinate.longitude,coordinate.latitude];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:coordinateStr forKey:@"coordinate"];
    
    __weak typeof(self) weakSelf = self;
    [DataService requestUrl:geo_to_address httpMethod:@"GET" params:params block:^(id result) {
        __strong typeof(weakSelf) strongSelf = weakSelf;    //再转换为强指针
        
        NSArray *geos = [result objectForKey:@"geos"];
        if (geos.count > 0) {
            NSDictionary *geo = [geos lastObject];
            
            NSString *addr = [geo objectForKey:@"address"];
            
            strongSelf.locationLabel.hidden = NO;   //让地理位置显示
            strongSelf.locationLabel.text = [NSString stringWithFormat:@"我的位置：%@",addr];
        }
        
    }];
    
//    //二 iOS自己内置
//    
//    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
//    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
//        
//        CLPlacemark *place = [placemarks lastObject];
//        NSLog(@"%@",place.name);
//        
//    }];

}


#pragma mark 选择照片

/**
 * 选择照片
 */
- (void)selectPhoto{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"相册", nil];
    
    [actionSheet showInView:self.view];
    
}


/**
 * 代理方法
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    UIImagePickerControllerSourceType sourceType;
    //选择相机 或者 相册
    if (buttonIndex == 0) {//拍照
        
        sourceType = UIImagePickerControllerSourceTypeCamera;
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if (!isCamera) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"摄像头无法使用" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
            
            return;
        }
        
        
    }else if(buttonIndex == 1){ //选择相册
        
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        
    }else{
        
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = sourceType;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
    
}

/**
 * 照片选择代理
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //弹出相册控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
    //2 取出照片
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //3 显示缩略图
    
    if (_zoomImageView == nil) {
        
        _zoomImageView = [[ZoomImageView alloc] initWithImage:image];
        _zoomImageView.frame = CGRectMake(10, _inputView.bottom + 10, 80, 80);
        [self.view insertSubview:_zoomImageView belowSubview:_toolBar];
        
        _zoomImageView.delegate = self;
    }
    _zoomImageView.image = image;
    _sendImage = image;
    
    [_inputView becomeFirstResponder];
    
}

#pragma mark 放大缩小图片 代理

//当图片放大时候键盘隐藏,缩小的时候键盘恢复
- (void)imageWillZoomOut:(ZoomImageView *)imageView{
    
    [_inputView becomeFirstResponder];
    
}
- (void)imageWillZoomIn:(ZoomImageView *)imageView{
    [_inputView resignFirstResponder];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (_inputView.isFirstResponder) {
        [_inputView resignFirstResponder];
    }else{
        [_inputView becomeFirstResponder];
    }
}




@end
